package simplega;

import simplega.SimpleGeneticAlgorithm;
import simplega.Chromosome;

import java.util.List;

// File: textGenetic.java
// This file contains a text-mode test program
// for class Genetic.

public class TestGenetic2 {

    static MyGenetic2 genetic_experiment;

    static public void main(String args[]) {
        // chromosomes with 10 1 bit genes 
        // population of 12 chromosomes:
        genetic_experiment = new MyGenetic2(4, 4, 0.85f, 0.3f);
        int geneIndex = 0; 
        for (Chromosome ll  : genetic_experiment.chromosomes) {
          System.out.println(ll.chromosome + " : " + genetic_experiment.decode(geneIndex++));
        }
        int NUM_CYCLES = 20;
       
        for (int i=0; i<NUM_CYCLES; i++) {
            genetic_experiment.evolve();
            System.out.println("Generation " + i);
            genetic_experiment.calcStatistic();
            //store best value and it's best fitness of each generation into an array
            }
    }
}

class MyGenetic2 extends SimpleGeneticAlgorithm {
    MyGenetic2(int num_g, int num_c, float crossover_fraction,
              float mutation_fraction) {
        super(num_g, num_c, crossover_fraction, mutation_fraction);
    }
    private int fitness(int x) {
        return (int)(Math.pow(x, 2));
    }
    
    int decode(int chromosomeIndex) {
        int base = 1;
        int x = 0;
        for (int j=0; j<numGeneOfChrom; j++)  {
            if (getGene(chromosomeIndex, j)) {
                x += base;
            }
            base *= 2;
        }
        return x;
    }
    public void calcFitness() {
        for (int i=0; i<numChromosome; i++) {
            int x = decode(i);
            chromosomes.get(i).setFitness(fitness(x));
        }
    }
    
    public void calcStatistic() {  
		// TODO Auto-generated method stub
		float sum = 0.0f;
        for (int i=0; i<numChromosome; i++) {
            int x = decode(i);
            sum += chromosomes.get(i).getFitness();
            System.out.print("Fitness for chromosome ");
            System.out.print(i);
            System.out.print(" is ");
            System.out.println(chromosomes.get(i).getFitness() + ", occurs at x=" + x);
            
        }
        sum /= (float)numChromosome;
        System.out.println("Average fitness=" + sum +
        		           " and best fitness for this generation:" +
        		           chromosomes.get(0).getFitness());
	}	
    
}
